﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using BLL;
using Model;
using System.Data;
using System.Data.SqlClient;
using Common;
using System.Text;
using System.Configuration;
using System.Xml;

namespace WebPortal.Controllers
{
    public class ModelConfigController : BaseController
    {
        #region 页面
        /// <summary>
        /// 模型首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string dbName)
        {
            PageRole role = new PageRole();
            role.role = SysPublicBLL.GetUserRole(Request.Cookies["MDM_UserName"].Value, dbName);
            return View(role);
        }
        public ActionResult EditViewScript()
        {
            return View();
        }
        public ActionResult ConfigRecordList(string dbName)
        {
            PageRole role = new PageRole();
            role.role = SysPublicBLL.GetUserRole(Request.Cookies["MDM_UserName"].Value, dbName);
            return View(role);
        }
        /// <summary>
        /// 引用模型页面
        /// </summary>
        /// <returns></returns>
        public ActionResult ModelList(string dbName)
        {
            PageRole role = new PageRole();
            role.role = SysPublicBLL.GetUserRole(Request.Cookies["MDM_UserName"].Value, dbName);
            return View(role);
        }
        /// <summary>
        /// 编辑模型页面
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult Edit(string modelID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            if (string.IsNullOrEmpty(modelID))//添加页面
                return View(new Model.ModelConfig());
            else//修改页面
            {
                return View(bll.GetItem(modelID));
            }
        }
        public ActionResult EditColumnInfo()
        {
            return View();
        }
        public ActionResult EditViewColumn()
        {
            return View();
        }
        public ActionResult EditColumn()
        {
            return View();
        }
        public ActionResult RefModelList()
        {
            return View();
        }
        public ActionResult CopyModel(string modelID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            if (string.IsNullOrEmpty(modelID))//添加页面
                return View(new Model.ModelConfig());
            else//修改页面
            {
                return View(bll.GetItem(modelID));
            }
        }
        public ActionResult SendModel(string modelID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            if (string.IsNullOrEmpty(modelID))//添加页面
                return View(new Model.ModelConfig());
            else//修改页面
            {
                return View(bll.GetItem(modelID));
            }
        }
        public ActionResult End(string modelID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            if (string.IsNullOrEmpty(modelID))
                return View(new Model.ModelConfig());
            else
            {
                return View(bll.GetItem(modelID));
            }
        }
        /// <summary>
        /// 模型分类编辑页面
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult EditType(string id, string dbName)
        {
            if (string.IsNullOrEmpty(id))//添加页面
                return View(new Model.DictionaryInfo());
            else//修改页面
            {
                LoginInfo loginInfos = base.loginInfo();
                loginInfos.DBName = dbName;
                ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
                DictionaryInfo model = bll.GetModelType(id);
                return View(model);
            }
        }
        public ActionResult GetModelData()
        {
            return View();
        }
        #endregion
        #region 模型管理
        /// <summary>
        /// 获取模型分类信息 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult GetType(string GUID, string type, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            List<ModelConfig> list = new List<ModelConfig>();
            if (type == "dict")
            {
                DictionaryInfo dictModel = bll.GetModelType(GUID);
                if (dictModel.Guid != null)
                {
                    ModelConfig model = new ModelConfig();
                    model.GUID = dictModel.Guid;
                    model.TableName = model.DefaultView = dictModel.Name;
                    model.TableDescription = dictModel.Description;
                    model.CreateTime = dictModel.CreaTetime.ToString("yyyy-MM-dd");
                    list.Add(model);
                }
            }
            else if (type == "model")
            {
                ModelConfig model = bll.GetItem(GUID);
                model.DefaultView = model.TableName;
                list.Add(model);
            }
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", list.Count);
            jsonDict.Add("rows", list);

            return Json(jsonDict);
        }

        public ActionResult GetTypeByModelID(string modelID, string type, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            List<ModelConfig> list = new List<ModelConfig>();
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            try
            {
                if (type == "dict")
                {
                    var modeTypes = bll.GetModelTypesByModelID(modelID);
                    foreach (var dictModel in modeTypes)
                    {
                        if (dictModel.Guid != null)
                        {
                            ModelConfig model = new ModelConfig();
                            model.GUID = dictModel.Guid;
                            model.TableName = model.DefaultView = dictModel.Name;
                            model.TableDescription = dictModel.Description;
                            model.CreateTime = dictModel.CreaTetime.ToString("yyyy-MM-dd");
                            list.Add(model);
                        }
                    }
                }

                jsonDict.Add("total", list.Count);
                jsonDict.Add("rows", list);
            }
            catch (Exception ex)
            {
                jsonDict.Add("msg", ex.Message);

            }

            return Json(jsonDict);
        }

        /// <summary>
        /// 取模型列表
        /// </summary>
        /// <param name="modelTypeId">模型类型</param>
        /// <param name="tableName">表名</param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public ActionResult GetList()
        {
            string tableName = Request.Params["tableName"];
            string dbName = Request.Params["dbName"];
            string step = Request.Params["step"];
            string getSysName = Request.Params["getSysName"];

            if (string.IsNullOrEmpty(step))
                step = "1";
            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            if (string.IsNullOrEmpty(sort))
                sort = "CreateTime";
            string rows = Request.Params["rows"];
            string page = Request.Params["page"];
            string expIDs = Request.Params["ExpIDs"];
            string tarSysID = Request.Params["tarSysID"];
            string typeID = Request.Params["typeID"];
            if (string.IsNullOrEmpty(expIDs))
                expIDs = "";
            //列表数据
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);

            SqlParameter[] pare = new SqlParameter[]{
            new SqlParameter("@TableName",tableName), 
            new SqlParameter("@ExpIDs",expIDs), 
            new SqlParameter("@tarSysID",tarSysID), 
            new SqlParameter("@TypeID",typeID),  
            new SqlParameter("@Step",step), 
            new SqlParameter("@Order",order),
            new SqlParameter("@Sort",sort.Replace("DefaultView","TableName")),
            new SqlParameter("@Rows",rows),
            new SqlParameter("@PageNum",page)
            };

            IList<ModelConfig> list = bll.GetList(pare);
            foreach (ModelConfig model in list)
            {
                model.DefaultView = model.TableName;
                if (model.Type == "1")
                {
                    if (typeID == "1")
                        model.TableName = string.Format("<img src='/images/tree_folder.gif' />{0}", model.TableName);
                    else
                        model.TableName = string.Format("<img src='/images/tree_folder.gif' /><a href='#' onclick='ViewList(\"{0}\",\"{1}\");'>{1}</a>", model.GUID, model.TableName);
                    model.TableType = "";
                }
                else
                {
                    model.TableType = string.Format("<img src='/images/step{0}.png' />", model.Step);
                    if (model.Status == 0)
                    {
                        model.TableType = "<img src='/images/stepdis.png' />";
                    }
                    model.TableName = string.Format("<img src='/images/tree_file.gif' /><a href='#' onclick='ModelTableInfo(\"{0}\",\"{1}\");'>{1}</a>", model.GUID, model.TableName);
                }
                model.IsRecord = model.IsRecord == "1" ? "<img src='/images/silk/tick.png' />" : "";
            }
            string count = "0";
            if (list.Count > 0)
                count = list[0].count;
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", count);
            jsonDict.Add("rows", list);

            return Json(jsonDict);
        }
        /// <summary>
        /// 模型配置版本列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRecordList()
        {
            string tableName = Request.Params["tableName"];
            string version = Request.Params["Version"];
            string ModelID = Request.Params["ModelID"];
            string dbName = Request.Params["dbName"];

            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            if (string.IsNullOrEmpty(sort))
                sort = "VersionTime";
            int rows = int.Parse(Request.Params["rows"]);
            int page = int.Parse(Request.Params["page"]);
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);

            SqlParameter[] pare = new SqlParameter[]{
            new SqlParameter("@ModelID",ModelID), 
            new SqlParameter("@TableName",tableName??""), 
            new SqlParameter("@Version",version??""),   
            new SqlParameter("@Rows",rows),
            new SqlParameter("@PageNum",page)
            };

            IList<ModelConfig> list = bll.GetVersionList(pare);
            foreach (ModelConfig model in list)
            {
                if (model.TableName.Length > 50)
                    model.TableName = model.TableName.Substring(0, 50);
                if (model.TableDescription.Length > 50)
                    model.TableDescription = model.TableDescription.Substring(0, 50);
                model.DefaultView = model.TableName;

                if (model.Status == 0)
                {
                    model.TableType = "<img src='/images/stepdis.png' />";
                }
                model.TableName = string.Format("<img src='/images/tree_file.gif' /><a href='#' onclick='ModelTableInfo(\"{0}\",\"{1}\",\"{2}\");'>{1}</a>", ModelID, model.TableName, model.Version);

            }
            string count = "0";
            if (list.Count > 0)
                count = list[0].count;
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", count);
            jsonDict.Add("rows", list);

            return Json(jsonDict);
        }
        /// <summary>
        /// Get Model 表集合
        /// </summary> 
        /// <returns></returns>
        public ActionResult GetRefModelList()
        {
            string modelID = Request.Params["modelID"];
            string dbName = Request.Params["dbName"];

            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            int rows = int.Parse(Request.Params["rows"]);
            int page = int.Parse(Request.Params["page"]);
            if (string.IsNullOrEmpty(sort))
                sort = "CreateTime";
            if (string.IsNullOrEmpty(order))
                order = "desc";

            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);

            SqlParameter[] pare = new SqlParameter[]{   
            new SqlParameter("@ModelID",modelID),  
            new SqlParameter("@Rows",rows),
            new SqlParameter("@PageNum",page)
            };

            IList<ModelConfig> list = bll.GetRefModelList(pare, sort, order);

            string count = "0";
            if (list.Count > 0)
                count = list[0].count;
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", count);
            jsonDict.Add("rows", list);

            return Json(jsonDict);
        }

        /// <summary>
        /// 保存模型分类
        /// </summary> 
        /// <returns></returns>
        public ActionResult SaveTypeData()
        {
            Dictionary<string, object> dict_para = new Dictionary<string, object>();
            dict_para.Add("GUID", Request.Params["id"]);
            dict_para.Add("Name", Request.Params["Name"].Trim());
            dict_para.Add("Description", Request.Params["Description"].Trim());
            dict_para.Add("ModelList", Request.Params["ModelList"]);
            dict_para.Add("dbName", Request.Params["dbName"]);
            bool IsUpdate = true;
            if (string.IsNullOrEmpty(Request.Params["id"]))
            {
                dict_para["GUID"] = Guid.NewGuid().ToString();
                IsUpdate = false;
            }

            dict_para.Add("IsUpdate", IsUpdate);
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = Request.Params["dbName"];
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            try
            {
                if (IsUpdate)//更新
                {
                    new SysOperationLog(loginInfos).Log("模型分类", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功,
                        "更新模型分类信息操作,操作成功,ID=" + Request.Params["id"], Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                }
                else//新增
                {
                    new SysOperationLog(loginInfos).Log("模型分类", Request.UserHostAddress, OperationAction.添加, OperationStatus.成功,
                        "添加模型分类操作,操作成功,ID=" + Request.Params["id"], Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                }

                bll.UpdateModelType(dict_para);
                return Json("1");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        public ActionResult AddModelToType()
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = Request.Params["dbName"];
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            try
            {
                string tyid = Request.Params["id"];
                string[] ids = Request.Params["ids"].Split(',');
                foreach (string modelid in ids)
                {
                    SqlParameter[] para = new SqlParameter[]{
                    new SqlParameter("@TypeID",tyid),
                    new SqlParameter("@ModelID",modelid)
                    };
                    bll.AddModelToType(para);
                }
                return Json("1");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        /// <summary>
        /// 删除模型信息
        /// </summary> 
        /// <returns></returns>
        public ActionResult Delete()
        {
            string id = Request.Params["id"];
            string ids = Request.Params["ids"];
            string Type = Request.Params["Type"];
            string dbName = Request.Params["dbName"];
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            try
            {
                if (Type == "1")
                {
                    return Json(bll.DeleteModelType(id));
                }
                else if (Type == "3")
                {
                    if (string.IsNullOrEmpty(ids))
                        return Json(bll.RemoveModelFromType(id));
                    else
                        return Json(bll.RemoveModelFromType(ids));
                }
                else
                {
                    return Json(bll.DeleteModel(id));
                }
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
            return Json("");
        }
        /// <summary>
        /// 删除历史版本
        /// </summary>
        /// <returns></returns>
        public ActionResult DeleteRecord()
        {
            string id = Request.Params["id"];
            string version = Request.Params["version"];
            string dbName = Request.Params["dbName"];
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            try
            {
                return Json(bll.DeleteRecord(id, version));
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        /// <summary>
        /// 执行模型最后一步
        /// </summary>
        /// <param name="modelID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult RunScript(string modelID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            try
            {
                int r = bll.RunScript(modelID);
                if (r == 6)
                    new SysOperationLog(loginInfos).Log("模型管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功,
                                         "执行模型最后一步,操作成功,ID=" + modelID, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                return Json(r);
            }
            catch (Exception ex)
            {
                new SysOperationLog(loginInfos).Log("模型管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.失败,
                      "执行模型最后一步,操作失败,ID=" + modelID + ";" + ex.Message, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                return Json(ex.Message);
            }

        }

        /// <summary>
        /// 保存模型信息
        /// </summary> 
        /// <returns></returns>
        public ActionResult SaveModelData()
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = Request.Params["dbName"];
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            List<string> msg = new List<string>();


            Dictionary<string, object> dict_para = new Dictionary<string, object>();
            dict_para.Add("GUID", Request.Params["id"]);
            dict_para.Add("Name", Request.Params["Name"].Trim());
            dict_para.Add("Description", Request.Params["Description"].Trim());
            dict_para.Add("IsRecord", Request.Params["IsRecord"].Trim());
            dict_para.Add("AddType", Request.Params["AddType"]);
            dict_para.Add("ModelRefID", Request.Params["ModelRefID"]);
            dict_para.Add("dbName", Request.Params["dbName"]);
            bool IsUpdate = true;
            if (string.IsNullOrEmpty(Request.Params["id"]))
            {
                dict_para["GUID"] = Guid.NewGuid().ToString();
                IsUpdate = false;
            }
            if (bll.CheckModelName(Request.Params["Name"].Trim(), dict_para["GUID"].ToString()) > 0)
            {
                return Json("操作失败！存在相同的模型名称。");
            }

            dict_para.Add("IsUpdate", IsUpdate);

            try
            {
                int update = bll.UpdateModel(dict_para);
                if (update == 1)
                {
                    string modelID = dict_para["GUID"].ToString();
                    bll.DeleteModelTypeByModelID(modelID);//清除旧类型记录
                    string modelTypeID = Request.Params["ModelTypeID"];
                    if (!string.IsNullOrEmpty(modelTypeID))
                    {
                        string[] typeIDs = modelTypeID.Split(',');
                        foreach (string id in typeIDs)
                        {
                            bll.AddModelTypeID(modelID, id);
                        }
                    }
                    if (IsUpdate)
                        new SysOperationLog(loginInfos).Log("模型管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功,
                            "更新模型操作,操作成功,ID=" + modelID, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                    else
                        new SysOperationLog(loginInfos).Log("模型管理", Request.UserHostAddress, OperationAction.添加, OperationStatus.成功,
                                           "添加模型操作,操作成功,ID=" + modelID, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");

                    msg.Add("ok");
                    msg.Add(dict_para["GUID"].ToString());
                    return Json(msg);
                }
                else
                {
                    msg.Add("2");
                    msg.Add(dict_para["GUID"].ToString());
                    return Json(msg);
                }
            }
            catch (Exception ex)
            {
                msg.Add(ex.Message);
                return Json(msg);
            }
        }
        /// <summary>
        /// 保存发送到实例模型信息
        /// </summary> 
        /// <returns></returns>
        public ActionResult SendModelConfig()
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = Request.Params["SendDB"];
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            EtlSourceSystemBLL sourcesystemBll = new EtlSourceSystemBLL(loginInfos);
            List<string> msg = new List<string>();
            var par = new SqlParameter[] { new SqlParameter("@SourceSysName", Request.Params["SysName"]) };
            if (sourcesystemBll.GetSourceSystemByName(par))
            {
                msg.Add("alert");
                msg.Add("操作失败！在目标实例存在相同的源系统名称。");
                return Json(msg);
            }
            if (bll.CheckModelName(Request.Params["ModelName"].Trim(), "1") > 0)
            {
                msg.Add("alert");
                msg.Add("操作失败！在目标实例存在相同的模型名称。");
                return Json(msg);
            }
            string modelRefID = Request.Params["ModelRefID"];
            string newModelID = Guid.NewGuid().ToString();

            SqlParameter[] para = new SqlParameter[] { 
                new SqlParameter("@ModelID", newModelID)
               ,new SqlParameter("@RefModelID", modelRefID)
               ,new SqlParameter("@ModelName", Request.Params["ModelName"])
               ,new SqlParameter("@Description", Request.Params["Description"]) 
               ,new SqlParameter("@SourceSysName", Request.Params["SysName"])
               ,new SqlParameter("@DBName", Request.Params["dbName"]) 
            };

            try
            {
                bll.SendModelConfig(para);

                //保存模型标签
                string modelTypeID = Request.Params["ModelTypeID"];
                if (!string.IsNullOrEmpty(modelTypeID))
                {
                    string[] typeIDs = modelTypeID.Split(',');
                    foreach (string id in typeIDs)
                    {
                        bll.AddModelTypeID(modelRefID, id);
                    }
                }
                new SysOperationLog(loginInfos).Log("模型管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功,
                    "发送模型配置操作,操作成功,ID=" + newModelID, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");

                msg.Add("ok");
                msg.Add(modelRefID);
                msg.Add(newModelID);
                return Json(msg);

            }
            catch (Exception ex)
            {
                msg.Add(ex.Message);
                return Json(msg);
            }
        }
        #endregion
        #region 模型字段
        /// <summary>
        /// 自动填充
        /// </summary>
        /// <param name="modelID">modelID</param>
        /// <param name="dbName">dbName</param>
        /// <returns></returns>
        public ActionResult GetSelectTableInfo(string modelID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            ModelConfig model = bll.GetItem(modelID);
            if (model.AddType == "Reference")
                modelID = model.ParentModelID;
            IList<ModelViewConfig> data = bll.GetTableInfo(modelID, "");//取表数据
            //string[] ckList = { "guid", "batchtime", "db_id", "isdelete" };
            for (int i = 0; i < data.Count; i++)
            {
                data[i].GUID = i.ToString();
                //ModelViewConfig tb = data[i];
                //if (ckList.Contains(tb.ColumnName.ToLower()))
                //{
                //    data.Remove(tb);
                //    i--;
                //}
            }
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", data.Count);
            jsonDict.Add("rows", data);

            return Json(jsonDict);
        }

        /// <summary>
        /// 取已配置模型字段信息
        /// </summary> 
        /// <returns></returns>
        public ActionResult GetModelColumn()
        {
            string modelID = Request.Params["modelID"];
            string version = Request.Params["version"];
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = Request.Params["dbName"];
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            IList<ModelViewConfig> allData = bll.GetModelColumn(modelID, version);//取表数据
            IList<ModelViewConfig> data = new List<ModelViewConfig>();
            for (int i = 0; i < allData.Count; i++)
            {
                bool push = true;
                ModelViewConfig model = allData[i];
                model.PK = model.ColumnIsBusinessPK == 1 ? "是" : "否";
                if (model.FactColumnName.Length > 32)
                    model.FactColumnName = model.FactColumnName.Substring(32);
                List<int> getIndexList = GetIndexList(allData, model.ColumnName);//存在多个字段源
                if (getIndexList.Count > 1)
                {
                    push = false;
                    if (getIndexList[0] == i)
                    {
                        push = true;
                        List<string> s = new List<string>();
                        List<string> t = new List<string>();
                        List<string> f = new List<string>();
                        List<string> c = new List<string>();
                        foreach (int j in getIndexList)
                        {
                            s.Add(allData[j].SourceSysName);
                            t.Add(allData[j].TableName);
                            if (allData[j].FactColumnName.Length > 32)
                                f.Add(allData[j].FactColumnName.Substring(32));
                            else
                                f.Add(allData[j].FactColumnName);
                            c.Add(allData[j].ColumnSourceID);
                        }
                        model.SourceSysName = string.Join("<br />&nbsp;", s);
                        model.TableName = string.Join("<br />&nbsp;", t);
                        model.FactColumnName = string.Join("<br />&nbsp;", f);
                        model.ColumnSourceID = string.Join("<br />&nbsp;", c);
                    }
                }
                if (push)
                    data.Add(model);
            }
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", data.Count);
            jsonDict.Add("rows", data);

            return Json(jsonDict);

        }
        public List<int> GetIndexList(IList<ModelViewConfig> data, string ColumnName)
        {
            List<int> list = new List<int>();
            for (int i = 0; i < data.Count; i++)
            {
                if (data[i].ColumnName.ToLower() == ColumnName.ToLower())
                    list.Add(i);
            }
            return list;
        }
        /// <summary>
        /// 更新模型字段信息
        /// </summary> 
        /// <returns></returns>
        public ActionResult SaveModelColumn()
        {
            string data = Request.Params["data"];
            string modelID = Request.Params["modelID"];
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            IList<ModelViewConfig> list = (IList<ModelViewConfig>)jsSerializer.Deserialize(data, typeof(IList<ModelViewConfig>));
            List<ETL_Source_View_ColumnEdit> ColumnTypeList = new List<ETL_Source_View_ColumnEdit>();
            List<ModelColumnConfig> modelList = new List<ModelColumnConfig>();
            IList<ModelColumnSourceConfig> modelSourceList = new List<ModelColumnSourceConfig>();
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = Request.Params["dbName"];
            int i = 0;
            #region 表字段信息处理
            int maxLength = 0;
            foreach (ModelViewConfig item in list)
            {
                ModelColumnConfig mt = modelList.Find(o => { return o.ColumnName.ToLower() == item.ColumnName.ToLower(); });
                if (mt == null)//modelList待保存表字段信息
                {
                    #region 存在多个字段源
                    List<int> getIndexList = GetIndexList(list, item.ColumnName);//存在多个字段源
                    if (getIndexList.Count > 1)
                    {
                        if (getIndexList[0] == i)
                        {
                            List<string> s = new List<string>();
                            List<string> t = new List<string>();
                            List<string> f = new List<string>();
                            List<string> c = new List<string>();
                            foreach (int j in getIndexList)
                            {
                                s.Add(list[j].SourceSysName);
                                t.Add(list[j].TableName);
                                f.Add(list[j].FactColumnName);
                                c.Add(list[j].ColumnSourceID);
                            }
                            item.SourceSysName = string.Join("&", s);
                            item.TableName = string.Join("&", t);
                            item.FactColumnName = string.Join("&", f);
                            item.ColumnSourceID = string.Join("&", c);
                        }
                    }
                    #endregion

                    //数据类型
                    ColumnTypeList.Add(new ETL_Source_View_ColumnEdit() { ColumnName = item.ColumnName, ColumnType = item.ColumnType });

                    string ModelColumnGUID = Guid.NewGuid().ToString();
                    List<string> cs = item.ColumnSourceID.Split("&").ToList();
                    List<string> fc = item.FactColumnName.Split("&").ToList();
                    for (int j = 0; j < cs.Count(); j++)//多个数据源
                    {
                        ModelColumnSourceConfig modelSource = new ModelColumnSourceConfig();
                        modelSource.GUID = Guid.NewGuid().ToString();
                        modelSource.SourceChooseOrderID = j + 1;
                        modelSource.ModelColumnID = ModelColumnGUID;
                        modelSource.FactSchemaName = "Fact";
                        modelSource.FactTableName = "ODS_" + modelID;
                        modelSource.FactColumnName = string.Format("{0}{1}", cs[j].Replace("-", ""), fc[j]);
                        modelSource.CreateTime = modelSource.UpdateTime = modelSource.DeleteTime = DateTime.Now;
                        modelSourceList.Add(modelSource);
                    }
                    ModelColumnConfig model = new ModelColumnConfig();//模型字段信息
                    model.GUID = ModelColumnGUID;
                    model.ModelTableID = modelID;
                    model.ColumnOrderID = i;
                    model.ColumnName = item.ColumnName;
                    model.ColumnDescription = item.ColumnDescription;
                    model.ColumnIsBusinessPK = item.PK == "是" ? 1 : 0;
                    model.CreateTime = model.UpdateTime = model.DeleteTime = DateTime.Now;
                    string[] typeArr = item.ColumnType.Replace(")", "").Split('(');
                    model.ColumnType = typeArr[0].ToLower();
                    if (typeArr.Length > 1)
                    {
                        string[] lengthArr = typeArr[1].Split(',');
                        if (lengthArr.Length == 1)
                        {
                            if (lengthArr[0].ToUpper().Equals("MAX"))
                            {
                                model.ColumnLength = -1;
                            }
                            else
                            {
                                model.ColumnLength = int.Parse(lengthArr[0]);
                            }
                        }
                        else
                        {
                            if (item.ColumnType.IndexOf("numeric") > -1 || item.ColumnType.IndexOf("decimal") > -1)
                            {
                                model.ColumnLength = int.Parse(lengthArr[0]);
                                model.ColumnPrecision = int.Parse(lengthArr[0]);
                                model.ColumnScale = int.Parse(lengthArr[1]);
                            }
                        }
                    }
                    if (model.ColumnType.ToLower() == "char" || model.ColumnType.ToLower() == "nchar")
                    {
                        maxLength += model.ColumnLength;
                    }
                    if (maxLength > 8060)
                        return Json("字段类型总长度超过了最大限8060，请检查字段类型配置。");
                    modelList.Add(model);//表字段信息
                }
                i++;
            }
            #endregion
            string ct_msg = SysPublicBLL.CheckType(ColumnTypeList);//判断数据类型
            if (ct_msg != "1")
            {
                return Json(ct_msg);
            }

            DataTable dt = DBConvert.ConvertToDataTable(modelList);
            DataTable dts = DBConvert.ConvertToDataTable(modelSourceList);
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            try
            {
                string m_Colid = bll.CheckModelColumn(modelID, dts);//检查模型字段中是否有引用不存在的表。
                if (m_Colid == "1")
                    return Json(bll.UpdateColumn(modelID, dt, dts).ToString());
                else
                {
                    ModelColumnConfig m_Name = modelList.Find(o => { return o.GUID == m_Colid; });
                    return Json("操作失败！模型字段：" + m_Name.ColumnName + " 引用了不存在的表，请检查配置。");
                }
            }
            catch (Exception ex) { return Json(ex.Message); }

            #region 注释
            //IList<ModelColumnSourceConfig> data4 = new List<ModelColumnSourceConfig>();
            //SysPublicBLL bll = new SysPublicBLL(loginInfos);
            //int i = 0;
            //foreach (var item in list)//表字段信息处理
            //{
            //    //if (!bll.CheckType(item.ColumnType, item.ColumnName))
            //    //{
            //    //    return item.ColumnName + "的字段类型" + item.ColumnType + "格式不正确，请检查!";
            //    //}

            //    ModelColumnConfig model = new ModelColumnConfig();

            //    model.GUID = Guid.NewGuid().ToString();
            //    model.ModelTableID = modelID;
            //    model.ColumnOrderID = i;
            //    model.ColumnName = item.ColumnName;
            //    model.ColumnDescription = item.ColumnDescription;
            //    model.ColumnType = item.ColumnType;
            //    model.ColumnIsBusinessPK = item.ColumnIsBusinessPK;
            //    modelList.Add(model);//表字段信息

            //    
            //    //model1.ColumnIsNullable = item.IsNull;
            //    //model1.ColumnDefaultValue = string.IsNullOrEmpty(item.ColumnDefaultValue) ? "" : item.ColumnDefaultValue;
            //    //model1.ColumnFixValue = string.IsNullOrEmpty(item.ColumnFixValue) ? "" : item.ColumnFixValue;
            //    //model1.ColumnParendID = string.IsNullOrEmpty(item.ColumnParendID) ? "" : item.ColumnParendID;
            //    //model1.CreateTime = DateTime.Now;
            //    //model1.UpdateTime = DateTime.Now;
            //    //model1.DeleteTime = DateTime.Now;



            //    //data4.Add(new ModelColumnSourceConfig()//原表字段信息-首选字段
            //    //{
            //    //    GUID = Guid.NewGuid().ToString(),
            //    //    SourceChooseOrderID = 1,
            //    //    ModelColumnID = model1.GUID,
            //    //    FactSchemaName = "Fact",
            //    //    FactTableName = factTableName,
            //    //    FactColumnName = item.FactColumnName1,
            //    //    CreateTime = DateTime.Now,
            //    //    UpdateTime = DateTime.Now,
            //    //    DeleteTime = DateTime.Now
            //    //});
            //    //原表字段信息-首选字段2
            //    //if (!string.IsNullOrEmpty(item.FactColumnName2) && !item.FactColumnName2.Equals("--请选择--"))
            //    //{
            //    //    data4.Add(new ModelColumnSourceConfig()
            //    //    {
            //    //        GUID = Guid.NewGuid().ToString(),
            //    //        SourceChooseOrderID = 2,
            //    //        ModelColumnID = model1.GUID,
            //    //        FactSchemaName = "Fact",
            //    //        FactTableName = factTableName,
            //    //        FactColumnName = item.FactColumnName2,
            //    //        CreateTime = DateTime.Now,
            //    //        UpdateTime = DateTime.Now,
            //    //        DeleteTime = DateTime.Now
            //    //    });
            //    //}
            //    ////原表字段信息-首选字段3
            //    //if (!string.IsNullOrEmpty(item.FactColumnName3) && !item.FactColumnName3.Equals("--请选择--"))
            //    //{
            //    //    data4.Add(new ModelColumnSourceConfig()
            //    //    {
            //    //        GUID = Guid.NewGuid().ToString(),
            //    //        SourceChooseOrderID = 3,
            //    //        ModelColumnID = model1.GUID,
            //    //        FactSchemaName = "Fact",
            //    //        FactTableName = factTableName,
            //    //        FactColumnName = item.FactColumnName3,
            //    //        CreateTime = DateTime.Now,
            //    //        UpdateTime = DateTime.Now,
            //    //        DeleteTime = DateTime.Now
            //    //    });
            //    //}
            //    

            //    i++;
            //}

            //foreach (var item in data3)
            //{
            //    if (!string.IsNullOrEmpty(item.ColumnParendID))
            //    {
            //        item.ColumnParendID = data3.Where(p => p.ColumnName.Equals(item.ColumnParendID)).FirstOrDefault().GUID;
            //    }
            //}

            //ModelConfigTransData transData = new ModelConfigTransData();
            //transData.ModelConfig = data1;
            //transData.ModelColumnConfigList = data3;
            //transData.ModelColumnSourceConfigList = data4;

            //ModelConfigBLL mbll = new ModelConfigBLL(loginInfos);
            ////保存表字段信息 
            //if (mbll.Update(transData, 0, oldModelType, oldTableName))
            //{
            //    return data1.GUID;
            //}
            //else
            //{
            //    return "-1";
            //}
            #endregion
        }
        /// <summary>
        /// 取表达式列表
        /// </summary>
        /// <param name="columnid"></param>
        /// <returns></returns>
        public ActionResult GetColumnExpression(string columnid, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            return Json(bll.GetColumnExpression(columnid));
        }
        public ActionResult GetALLColumnTypeList()
        {
            LoginInfo loginInfos = base.loginInfo();
            EtlSourceSystemBLL sourceSystemBLL = new EtlSourceSystemBLL(loginInfos);
            return Json(sourceSystemBLL.GetALLColumnTypeList());
        }
        /// <summary>
        /// 取已配置模型字段信息
        /// </summary> 
        /// <returns></returns>
        public ActionResult GetViewColumn()
        {
            string modelID = Request.Params["modelID"];
            string version = Request.Params["version"];
            string isDQ = Request.Params["isDQ"];
            string isScript = Request.Params["isScript"];
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = Request.Params["dbName"];
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            TableInfoBLL tbll = new TableInfoBLL(loginInfos);
            //IList<ModelViewConfig> data = bll.GetTableInfo(modelID, "");//取表数据
            IList<ModelViewConfig> data = new List<ModelViewConfig>();
            if (isDQ == "1")
                data = bll.GetTableInfo(modelID, "");//取表字段数据
            else if (isScript == "1")
                data = bll.GetModelColumn(modelID, "");//取模型字段数据
            else
                data = tbll.GetModelViewInfo(modelID, version);//去扩展模型字段数据
            List<ModelViewConfig> newdata = new List<ModelViewConfig>();
            IList<ModelColumnExpression> mcexp = bll.GetColumnExpressionByModelID(modelID, version);
            foreach (ModelViewConfig model in data)
            {
                if (isDQ == "1" || newdata.FindIndex(o => { return o.GUID == model.GUID; }) == -1)
                {
                    model.PK = model.ColumnIsBusinessPK == 1 ? "是" : "否";
                    model.ColumnIsNullable = model.PK == "是" ? "否" : "是";
                    if (string.IsNullOrEmpty(model.ColumnScriptExtend))
                        model.ColumnScriptExtend = "[" + model.ColumnName + "]";
                    List<string> exop = new List<string>();
                    List<string> exce = new List<string>();
                    List<int> exiv = new List<int>();
                    foreach (ModelColumnExpression mce in mcexp)
                    {
                        if (string.IsNullOrEmpty(version))
                        {
                            if (mce.ParentGUID.Equals(model.GUID, StringComparison.CurrentCultureIgnoreCase))
                            {
                                exop.Add(mce.ColumnOperator);
                                exce.Add(mce.ColumnExpression);
                                exiv.Add(mce.IsValue);
                            }
                        }
                        else
                        {
                            if (mce.ParentGUID.Equals(model.ColumnSourceID, StringComparison.CurrentCultureIgnoreCase))
                            {
                                exop.Add(mce.ColumnOperator);
                                exce.Add(mce.ColumnExpression);
                                exiv.Add(mce.IsValue);
                            }
                        }
                    }
                    if (exop.Count() > 0)
                    {
                        model.Operator = string.Join("&", exop);
                        model.ColumnExpression = string.Join("&", exce);
                        model.IsValue = string.Join("&", exiv);
                    }
                    newdata.Add(model);
                }
            }
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", newdata.Count);
            jsonDict.Add("rows", newdata);

            return Json(jsonDict);

        }
        /// <summary>
        /// 添加模型-创建视图
        /// </summary> 
        /// <returns></returns>
        public ActionResult SaveExtendConfig()
        {
            string result = string.Empty;
            try
            {
                string jsonData = Request.Params["data"];
                string modelID = Request.Params["modelID"];
                string dbName = Request.Params["dbName"];
                //处理提交数据
                IList<ModelViewConfig> data = new List<ModelViewConfig>();
                DataTable dt = new DataTable();
                DataTable dtOpt = new DataTable();
                LoginInfo loginInfos = base.loginInfo();
                loginInfos.DBName = dbName;
                ModelColumnExtendConfigBLL bll = new ModelColumnExtendConfigBLL(loginInfos);
                IList<ModelColumnExpression> expList = new List<ModelColumnExpression>();

                if (!string.IsNullOrEmpty(jsonData) && !jsonData.Equals("[]"))
                {
                    JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                    data = (IList<ModelViewConfig>)jsSerializer.Deserialize(jsonData, typeof(IList<ModelViewConfig>));
                    dt = Common.DBConvert.ConvertToDataTable<ModelViewConfig>(data);
                    int orderID = 1;
                    foreach (DataRow item in dt.Rows)
                    {
                        string extID = Guid.NewGuid().ToString();
                        item["GUID"] = extID;
                        item["ColumnOrder"] = orderID.ToString();
                        item["ModelTableID"] = modelID;
                        item["ColumnIsBusinessPK"] = item["PK"].ToString() == "是" ? 1 : 0;
                        item["ColumnIsNullable"] = item["ColumnIsNullable"].ToString() == "是" ? "1" : "0";
                        string[] typeArr = item["ColumnType"].ToString().Replace(")", "").Split('(');
                        item["ColumnType"] = typeArr[0].ToLower();
                        string opt = item["Operator"].ToString();
                        if (!string.IsNullOrEmpty(opt))
                        {
                            IList<string> arrOpt = opt.Split('&').ToList();
                            IList<string> arrExp = item["ColumnExpression"].ToString().Split('&').ToList();
                            IList<string> arriv = item["IsValue"].ToString().Split('&').ToList();
                            for (int i = 0; i < arrOpt.Count; i++)
                            {
                                ModelColumnExpression exp = new ModelColumnExpression();
                                exp.GUID = Guid.NewGuid().ToString();
                                exp.ParentGUID = extID;
                                exp.ColumnOperator = arrOpt[i];
                                exp.ColumnExpression = arrExp[i];
                                exp.IsValue = int.Parse(arriv[i]);
                                expList.Add(exp);
                            }
                        }
                        orderID++;
                    }
                    dtOpt = Common.DBConvert.ConvertToDataTable<ModelColumnExpression>(expList);
                }
                result = bll.SaveAndCreateView(dt, dtOpt, modelID).ToString();//保存
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return Json(result);
        }
        /// <summary>
        /// 检查模型脚本
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckModelScript()
        {
            string scriptText = Request.Params["scriptText"];
            string columnTypeList = Request.Params["columnTypeList"];
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            IList<ModelScript> list = (IList<ModelScript>)jsSerializer.Deserialize(columnTypeList, typeof(IList<ModelScript>));
            List<ColumnMapping> ColumnMappingList = new List<ColumnMapping>();
            XmlDocument dom = new XmlDocument();
            dom.Load(Server.MapPath("/Scripts/ColumnMapping.xml"));//装载XML文档 
            foreach (XmlElement item in dom.DocumentElement.ChildNodes)
            {
                ColumnMappingList.Add(new ColumnMapping { Name = item.Attributes["Name"].Value, Value = item.Attributes["value"].Value });
            }

            foreach (ModelScript item in list)
            {
                if (scriptText.IndexOf(item.ColumnName) > -1)
                {
                    string colType = item.ColumnType;
                    if (colType.IndexOf("(") > -1)
                        colType = colType.Substring(0, colType.IndexOf("("));
                    ColumnMapping cm = ColumnMappingList.Find(o => { return o.Name.ToString().ToLower() == colType; });//xml中字段类型对应的值
                    if (cm == null)
                        scriptText = scriptText.Replace(item.ColumnName, "'2014'");
                    else
                    {
                        if (item.ColumnType.StartsWith("date"))
                            scriptText = scriptText.Replace(item.ColumnName, string.Format("cast({0} as {1})", cm.Value, item.ColumnType));
                        else
                            scriptText = scriptText.Replace(item.ColumnName, cm.Value);
                    }
                }
            }
            List<string> msg = new List<string>();
            try
            {

                LoginInfo loginInfos = base.loginInfo();
                ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
                DataTable dt = bll.CheckModelScript(scriptText);
                if (dt != null && dt.Rows.Count > 0)
                {
                    msg.Add("1");
                    switch (dt.Columns[0].DataType.Name.ToLower())
                    {
                        case "decimal":
                            msg.Add("decimal(18.0)");
                            break;
                        case "double":
                            msg.Add("float");
                            break;
                        case "int32":
                            msg.Add("int");
                            break;
                        case "datetime":
                            msg.Add("datetime");
                            break;
                        default:
                            msg.Add("nvarchar(max)");
                            break;
                    }
                }
                else
                    msg.Add("无返回值。");
            }
            catch (Exception ex)
            {
                msg.Add(ex.Message);
            }
            return Json(msg);
        }
        #endregion
        #region 其他

        /// <summary>
        /// 模型表数据
        /// </summary>
        /// <param name="modelID"></param>
        /// <param name="viewName"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult GetModelTableData(string modelID, string dbName)
        {
            JsonResponse<string> jsonResponse = new JsonResponse<string>();
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            try
            {
                string order = Request.Params["order"];
                string sort = Request.Params["sort"];
                string checkbox = Request.Params["checkbox"];
                string query = Request.Params["query"];
                List<string> sql = new List<string>();
                IDataParameter[] sqlPara = null;
                if (!string.IsNullOrEmpty(query) && query != "[]")
                {
                    query = query.Replace("\"", "").Replace("[[", "").Replace("]]", "");
                    IEnumerable<string> arrList = query.Split("],[");

                    sqlPara = new SqlParameter[arrList.Count()];
                    int i = 0;
                    foreach (string str in arrList)
                    {
                        string[] item = str.Split(',');
                        switch (item[1])
                        {
                            case "like":
                            case "not like":
                                sql.Add(string.Format(" [{0}] {1} '%'+@{0}+'%' ", item[0], item[1]));
                                break;
                            case "is null":
                            case "is NOT null":
                                sql.Add(string.Format(" [{0}] {1} ", item[0], item[1]));
                                break;
                            case "in":
                            case "not in":
                                sql.Add(string.Format(" [{0}] {1} (@{0}) ", item[0], item[1]));
                                break;
                            default:
                                sql.Add(string.Format(" [{0}] {1} @{0} ", item[0], item[1]));// " column=@column"
                                break;
                        }
                        sqlPara[i] = new SqlParameter("@" + item[0], item[2]);
                        i++;
                    }
                }

                if (string.IsNullOrEmpty(sort))
                    sort = "desc";
                if (string.IsNullOrEmpty(order))
                    order = "";

                LoginInfo loginInfos = base.loginInfo();
                loginInfos.DBName = dbName ?? "";
                ModelConfigBLL BLL = new ModelConfigBLL(loginInfos);

                var html = new System.Text.StringBuilder();

                DataTable dt = BLL.GetModelDate(modelID, order, sort, sql.ToArray(), sqlPara);//sourceSystemBLL.GetSourceTableData(viewName, connstr, connType, order, sort, sql.ToArray(), para);
                jsonResponse.Data = SysPublicBLL.DataTableToString(dt, 0, order, sort, checkbox == "1" ? true : false, false, true);
                jsonResponse.Head = GetSourceTableHeadData(dt.Columns);

                jsonResponse.Success = true;
                jsonResponse.Message = "OK";
                return Json(jsonResponse);
            }
            catch (Exception ex)
            {
                //return "信息获取失败！" + ex.Message;
                jsonResponse.Success = false;
                jsonResponse.Message = "信息获取失败！" + ex.Message;
                jsonResponse.Data = "";
                return Json(jsonResponse);
            }
        }
        public string GetSourceTableHeadData(DataColumnCollection columnList)
        {
            StringBuilder sb = new StringBuilder();
            StringBuilder sbOpt = new StringBuilder();
            LoginInfo loginInfos = base.loginInfo();
            IList<Operator> optList = OperatorBLL.GetList();
            sbOpt.Append("<option value=''>-请选择-</option>");
            foreach (Operator o in optList)
            {
                sbOpt.Append("<option>" + o.LegalOperator + "</option>");
            }
            sb.Append("<table class='pagTable' cellpadding='0' cellspacing='0'>");
            foreach (DataColumn dc in columnList)
            {
                sb.Append(string.Format("<tr id='{0}'><td>{0}</td><td width='100px'><select class='sel_{0}'>{1}</select></td><td width='160px'><input width='150px' type='text' class='txt_{0}'></td></tr>", dc.ColumnName, sbOpt.ToString()));
            }
            sb.Append("</table>");
            return sb.ToString();
        }


        public ActionResult GetTransDataList(string id, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            return Json(bll.GetTransDataList(id));
        }
        public ActionResult GetFactTable(string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            FactTableBLL bll = new FactTableBLL(loginInfos);
            return Json(bll.GetList());
        }

        public string GetSelectedFactTableName(string id, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            return bll.GetFactTableName(id);
        }
        /// <summary>
        /// 取所有字段类型
        /// </summary>
        /// <returns></returns>
        public ActionResult GetColumnType(string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ColumnTypeBLL bll = new ColumnTypeBLL(loginInfos);
            return Json(bll.GetList());
        }

        /// <summary>
        /// 检查模型是否可删除
        /// </summary>
        /// <param name="guid">模型id</param>
        /// <returns></returns>
        public string CheckDelete(string guid, string dbName)
        {
            try
            {
                LoginInfo loginInfos = base.loginInfo();
                loginInfos.DBName = dbName;
                ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
                DataTable dt = bll.CheckDelete(guid);//取模型依赖信息
                if (dt != null && dt.Rows.Count > 0)
                {
                    string result = string.Empty;
                    switch (dt.Rows[0][0].ToString())
                    {
                        case "1":
                            result = "该模型有对接系统依赖不能删除！对接系统名称：" + dt.Rows[0][1].ToString();
                            break;
                        case "2":
                            result = "该模型有ETL任务不能删除！任务名称：" + dt.Rows[0][1].ToString();
                            break;
                        default:
                            result = "OK";
                            break;
                    }
                    return result;
                }
                else
                    return "删除失败！";
            }
            catch (Exception ex) { return ex.Message; }
        }

        /// <summary>
        /// 检查重复字段
        /// </summary>
        /// <param name="columnNames">提交字段</param>
        /// <returns></returns>
        public string RepeatColumnCheck(string columnNames, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            List<string> list_columnNames = columnNames.Split(',').ToList();//解析提交字段到数组
            long c;
            foreach (string name in list_columnNames)
            {
                c = list_columnNames.LongCount(o => { return o == name; });//验证提交字段内是否重复
                if (c > 1)
                    return "列名 " + name + " 重复!";
                else
                {
                    if (bll.RepeatColumnCheck(name))//验证提交字段在数据字典内是否重复
                        return "列名 " + name + " 与关键字重复!";
                }
            }
            return "";
        }
        public string CheckType(string typename, string columnName, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            SysPublicBLL bll = new SysPublicBLL(loginInfos);
            return bll.CheckType(typename, columnName) ? "1" : "0";
        }

        /// <summary>
        /// 检查字段是否存在
        /// </summary>
        /// <param name="guid">字段id</param>
        /// <param name="modelTableID">模型id</param>
        /// <param name="columnName">字段名称</param>
        /// <returns>1存在，0不存在</returns>
        public string ColumnNameIsExist(string guid, string modelTableID, string columnName, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelColumnExtendConfigBLL bll = new ModelColumnExtendConfigBLL(loginInfos);
            return bll.ColumnNameIsExist(guid, modelTableID, columnName) ? "1" : "0";
        }

        /// <summary>
        /// 模型视图页面初始化
        /// </summary>
        /// <param name="modelTableID">模型id</param>
        /// <returns></returns>
        public ActionResult ExtendEdit(string modelTableID)
        {
            ModelColumnExtendConfig data = new ModelColumnExtendConfig();
            data.ModelTableID = modelTableID;
            return View(data);
        }
        /// <summary>
        /// 取模型视图配置列表
        /// </summary>
        /// <param name="modelTableID">模型id</param>
        /// <returns></returns>
        public ActionResult GetExtendConfigList(string modelTableID, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelColumnExtendConfigBLL bll = new ModelColumnExtendConfigBLL(loginInfos);
            return Json(bll.GetList(modelTableID));
        }
        /// <summary>
        /// 检查视图名是否存在
        /// </summary>
        /// <param name="viewName">视图名</param>
        /// <param name="id">模型id</param>
        /// <returns></returns>
        public string ViewNameIsExist(string viewName, string id, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            return bll.ViewNameIsExist(viewName, id) ? "1" : "0";
        }
        /// <summary>
        /// 检查表名是否存在
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="modelTableCode">模型编码</param>
        /// <param name="id">模型id</param>
        /// <returns></returns>
        public int TableNameIsExist(string tableName, string modelTableCode, string id, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            return bll.TableNameIsExist(tableName, modelTableCode, id);
        }
        /// <summary>
        /// 取表字段列表
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public ActionResult SyncTableCloumns(string tableName, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            SysPublicBLL bll = new SysPublicBLL(loginInfos);
            List<SysNameValue> result = bll.GetTableInfoList(tableName);//取表数据
            if (result != null && result.Count > 0)
            {
                foreach (var item in result)
                {
                    item.Value = item.Name;
                    item.Name = ReplaceColumn(item.Name);
                }
                //去除字段
                result = RemoveReservedField(result, "GUID");
                result = RemoveReservedField(result, "BatchTime");
                result = RemoveReservedField(result, "DB_ID");
                result = RemoveReservedField(result, "ISDELETE");
            }
            result.Insert(0, new SysNameValue() { Name = "--请选择--", Value = "--请选择--" });
            return Json(result);
        }
        /// <summary>
        /// 取模型视图字段配置信息
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public ActionResult LoadByGuid(string guid, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelColumnExtendConfigBLL bll = new ModelColumnExtendConfigBLL(loginInfos);
            return Json(bll.LoadByGuid(guid));
        }
        /// <summary>
        /// 删除模型视图字段
        /// </summary>
        /// <param name="guid">视图id</param>
        /// <returns></returns>
        public string ColumnExtendConfigDelete(string guid, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelColumnExtendConfigBLL bll = new ModelColumnExtendConfigBLL(loginInfos);
            return bll.Delete(guid) ? "1" : "0";
        }


        public string ReplaceColumn(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return "";
            }
            else
            {
                return value.Replace("|!@#$%^&*|", "");
            }
        }
        /// <summary>
        /// 取字典值
        /// </summary>
        /// <param name="keyName"></param>
        /// <returns></returns>
        public ActionResult GetDropdowmListData(string keyName, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            return Json(bll.GetListByKeyName(keyName));
        }
        /// <summary>
        /// 取字典值
        /// </summary>
        /// <param name="keyName"></param>
        /// <returns></returns>
        public ActionResult GetMTListByKeyName(string keyName, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            return Json(bll.GetMTListByKeyName(keyName));
        }

        public string GetDictionaryName(string keyName, string value, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            return bll.GetNameByKeyNameAndValue(keyName, value);
        }

        private IList<TableInfo> RemoveReservedField(IList<TableInfo> data, string field)
        {
            IList<TableInfo> _temp = data.Where(p => p.ColumnName.Equals(field)).ToList();
            foreach (var item in _temp)
            {
                data.Remove(item);
            }
            return data;
        }

        private List<SysNameValue> RemoveReservedField(List<SysNameValue> data, string field)
        {
            IList<SysNameValue> _temp = data.Where(p => p.Name.Contains(field)).ToList();
            foreach (var item in _temp)
            {
                data.Remove(item);
            }
            return data;
        }

        public ActionResult GetModelTableNameList(string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ModelConfigBLL bll = new ModelConfigBLL(loginInfos);
            return Json(bll.GetModelTableNameList());
        }

        #region SelectMdel
        public ActionResult SelectMdel()
        {
            return base.View();
        }
        #endregion
        #endregion
    }
    public class ModelScript
    {
        public string ColumnName { get; set; }
        public string ColumnType { get; set; }
    }
    public class ColumnMapping
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }
}
